package com.itheima.bolee.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bolee.framework.commons.constant.basic.SuperConstant;
import com.itheima.bolee.insurance.pojo.Safeguard;
import com.itheima.bolee.insurance.mapper.SafeguardMapper;
import com.itheima.bolee.insurance.service.ISafeguardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.bolee.insurance.constant.SafeguardCacheConstant;
import com.itheima.bolee.insurance.dto.SafeguardVO;
import com.itheima.bolee.insurance.enums.SafeguardEnum;
import com.itheima.bolee.framework.commons.utils.BeanConv;
import com.itheima.bolee.framework.commons.utils.EmptyUtil;
import com.itheima.bolee.framework.commons.utils.ExceptionsUtil;
import com.itheima.bolee.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    /**
     * 构建多查询条件的方法
    * @description 保障项多条件组合
    * @param safeguardVO 保障项
    * @return QueryWrapper查询条件
    */
    private QueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO){
        //创建 QueryWrapper 查询条件对象
        QueryWrapper<Safeguard> safeguardQueryWrapper = new QueryWrapper<>();

        //条例键类型 "safeguardVO.safeguardType" 先不构建这个查询条件

        //条例键查询  "safeguardVO.safeguardKey"
        String safeguardKey = safeguardVO.getSafeguardKey();
        if(!EmptyUtil.isNullOrEmpty(safeguardKey)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getSafeguardKey,safeguardKey);
        }
        //条例键名称查询  "safeguardVO.safeguardKeyName"
        String safeguardKeyName = safeguardVO.getSafeguardKeyName();
        if(!EmptyUtil.isNullOrEmpty(safeguardKeyName)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getSafeguardKeyName,safeguardKeyName);
        }

        //条例值查询  "safeguardVO.safeguardVal"
        String safeguardVal = safeguardVO.getSafeguardVal();
        if(!EmptyUtil.isNullOrEmpty(safeguardVal)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getSafeguardVal,safeguardVal);
        }

        //排序查询  "safeguardVO.sortNo"
        Integer sortNo = safeguardVO.getSortNo();
        if(!EmptyUtil.isNullOrEmpty(sortNo)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getSortNo,sortNo);
        }

        //备注查询  "safeguardVO.remake"
        String remake = safeguardVO.getRemake();
        if(!EmptyUtil.isNullOrEmpty(remake)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getRemake,remake);
        }

        //状态查询  "safeguardVO.dataState"
        String dataState = safeguardVO.getDataState();
        if(!EmptyUtil.isNullOrEmpty(dataState)){
            safeguardQueryWrapper
                    .lambda()
                    .eq(Safeguard::getDataState,dataState);
        }

        //按创建时间降序
        safeguardQueryWrapper
                .lambda()
                .orderByDesc(Safeguard::getCreateTime);

        // 返回查询条件对象
        return safeguardQueryWrapper;
    }

    /**
     * 保障项分页查询
     * @param safeguardVO 保障项查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return
     */
    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE,key ="#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        try {
            //构建分页对象
            Page<Safeguard> safeguardPage = new Page<>(pageNum, pageSize);
            //构建分页查询条件
            QueryWrapper<Safeguard> safeguardQueryWrapper = this.queryWrapper(safeguardVO);
            //执行分页查询   page(E page, Wrapper<Safeguard> queryWrapper)  第一个参数：分页对象，第二个参数：分页查询条件
            Page<Safeguard> page = page(safeguardPage, safeguardQueryWrapper);
            //对象结果转换
            Page<SafeguardVO> safeguardVOPage = BeanConv.toPage(page, SafeguardVO.class);
            //返回结果
            return safeguardVOPage;
        }catch (Exception e){
            // 输出保障项分页查询异常信息
            log.error("保障项分页查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            // 抛出业务异常 枚举类 -> “查询保障项分页失败”
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC,key ="#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        try {
            //执行查询
            return BeanConv.toBean(getById(safeguardId),SafeguardVO.class);
        }catch (Exception e){
            log.error("保障项单条查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }

    /**
     * 保存保障项信息
     * @param safeguardVO 保障项查询条件
     * @return
     */
    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true)},
        put={@CachePut(value = SafeguardCacheConstant.BASIC,key = "#result.id")})
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try{
            // 对象转换 safeguardVo -> safeguard
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            // 调用mybatis-plus 中的 save() 进行数据库查询保障项数据的操作，返回一个boolean类型的变量 flag
            boolean flag = save(safeguard);
            // 如果flag == false 的话，说明向数据库中插入保障项信息失败，抛出异常 “保存保障项失败”
            if(flag == false){
                throw new RuntimeException("保存保障项失败");
            }
            //执行插入数据库操作成功后，对象转换  safeguard -> safeguardVo
            SafeguardVO safeguardVOHandler = BeanConv.toBean(safeguard, SafeguardVO.class);
            // 返回 safeguardVO对象
            return safeguardVOHandler;
        }catch (Exception e){
            // 输出保存保障项异常信息
            log.error("保存保障项异常：,{}",ExceptionsUtil.getStackTraceAsString(e));
            // 抛出业务异常 枚举类 -> "保存保障项失败"
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    /**
     * 修改保障项信息
     * @param safeguardVO 保障项对象
     * @return
     */
    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true),
        @CacheEvict(value = SafeguardCacheConstant.BASIC,key = "#safeguardVO.id")})
    public Boolean update(SafeguardVO safeguardVO) {
        try{
            //对象转换 safeguardVo -> safeguard
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //调用 mybatis-plus 中的updateById() 方法 更新数据库中保障项信息 ，返回boolean类型的数据
            boolean flag = updateById(safeguard);
            // 修改操作后返回的结果为false,说明未成功修改保障项信息，抛出业务异常“修改保障项失败”
            if (flag == false){
                throw new RuntimeException("修改保障项失败");
            }
            //返回结果
            return flag;
        }catch (Exception e){
            // 输出修改保障项异常信息
            log.error("修改保障项异常：{}",ExceptionsUtil.getStackTraceAsString(e));
            // 抛出业务异常  枚举类 -> 修改保障项失败
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = SafeguardCacheConstant.LIST,allEntries = true),
        @CacheEvict(value = SafeguardCacheConstant.BASIC,allEntries = true)})
    public Boolean delete(String[] checkedIds) {
        try{
            // 将在前端获取到的多个保障项id(String数组)，转为字符串列表 checkedIdsStringList
            List<String> checkedIdsStringList = Arrays.asList(checkedIds);
            //将字符串列表 checkedIdsStringList 转化为 Long 类型的列表 checkedIdsLongList
            List<Long> collect = checkedIdsStringList
                    .stream()
                    .map(s -> new Long(s))
                    .collect(Collectors.toList());
            List<Long> checkedIdsLongList = checkedIdsStringList
                    .stream()
                    .map(Long::new)
                    .collect(Collectors.toList());
            // 调用 mybatis-plus 中的 removeIds 方法删除指定 id 的保障项，并返回删除操作是否成功的标志
            boolean flag = removeByIds(checkedIdsLongList);
            // 如果删除操作失败，抛出运行时异常“删除保障项失败”
            if(flag == false){
                throw new RuntimeException("删除保障项失败");
            }
            //返回结果
            return flag;
        }catch (Exception e){
            // 输出删除保障项失败信息
            log.error("删除保障项失败：{}",ExceptionsUtil.getStackTraceAsString(e));
            // 抛出业务异常 “删除保障项失败”
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST,key ="#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            //构建查询条件
            QueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //执行列表查询
            List<SafeguardVO> safeguardVOs = BeanConv.toBeanList(list(queryWrapper),SafeguardVO.class);
            return safeguardVOs;
        }catch (Exception e){
            log.error("保障项列表查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
    }

    /**
     * 查询保障项列表
     * @param safeguardKeyList
     * @return
     */
    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST,key ="#safeguardKeyList.hashCode()")
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
       try{
           // 构造查询条件对象
           LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
           // 封装查询条件 调用查询条件对象的in() -> sql: safeguardKey in (... , ...)
           queryWrapper.in(Safeguard::getSafeguardKey, safeguardKeyList);
           // 封装查询条件 调用查询条件的eq()  -> dataState = "0"
           queryWrapper.eq(Safeguard::getDataState,SuperConstant.DATA_STATE_0);
           //执行列表查询 得   到 保障项信息列表
           List<Safeguard> safeguardsList = list(queryWrapper);
           //对象转换
           List<SafeguardVO> safeguardVOList = BeanConv.toBeanList(safeguardsList, SafeguardVO.class);
           //返回结果
           return safeguardVOList;
       }catch (Exception e){
           // 输出保障项列表查询异常信息
           log.error("保障项列表查询异常：{}",ExceptionsUtil.getStackTraceAsString(e));
           // 抛出业务异常 “查询保障项列表失败”
           throw new ProjectException(SafeguardEnum.LIST_FAIL);
       }
    }


    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC,key ="#safeguardKey")
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
            // 封装查询条件 调用查询条件对象的eq() -> sql: safeguardKey = ""
            queryWrapper.eq(Safeguard::getSafeguardKey,safeguardKey);
            // 封装查询条件 调用查询条件的eq() -> dataState = "0"
            queryWrapper.eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0);
            // 执行列表查询
            Safeguard safeguardOne = getOne(queryWrapper);
            // 对象转换 Safeguard -> SafeguardVo
            SafeguardVO safeguardVO = BeanConv.toBean(safeguardOne, SafeguardVO.class);
            //返回结果
            return safeguardVO;
        }catch (Exception e){
            // 输出保障项对象查询异常信息
            log.error("保障项对象查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            // 抛出异常信息 "查询保障项对象失败"
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }
}
